<?php
// +----------------------------------------------------------------------
// | HKCMS 标签行为，处理特殊标签({hkcms:script}{/hkcms:script},{hkcms:style}{/hkcms:style})
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------
namespace app\content\behavior;

use think\Request;

class Tags
{
    public function run(&$content)
    {
        $request = Request::instance();

        if ($request->module()=='content' && $request->controller()=='Index') {
            $style = '';
            $script = '';
            $result = preg_replace_callback("/{hkcms:(script|style)}[\s\S]*?{\/hkcms:(script|style)}/i", function ($match) use (&$style, &$script) {
                if (isset($match[1]) && in_array($match[1], ['style', 'script'])) {
                    ${$match[1]} .= str_replace(['{hkcms:style}','{/hkcms:style}','{hkcms:script}','{/hkcms:script}'], '', $match[0]);
                }

                return '';
            }, $content);

            $content = preg_replace_callback('/^\s+(\{__STYLE__\}|\{__SCRIPT__\})\s+$/m', function ($matches) use ($style, $script) {
                return $matches[1] == '{__STYLE__}' ? $style : $script;
            }, $result ? $result : $content);
        }
    }
}